package com.geek.javase.ch17.work.tcpwork.tcp7;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

/*
 *@Date 2025/11/4
 *@Author wangpeng
 *@Description
 * 需求7：实现一对多群聊，客户端写出消息，服务器端可以转发消息给其它客户端，其它客户端也可以读取消息
 */
public class TCPServer {
    //存储连接的客户端，线程安全
    private static CopyOnWriteArrayList<Socket> clints = new CopyOnWriteArrayList<>();
    //线程池能够处理的最大任务数
    //private static final int MAX_CLIENT = 3;
    private static final int MAX_CLIENT = 2;
    public static void main(String[] args) {
        System.out.println("-------服务器--------");
        ServerSocket ss = null;
        //创建线程池
        ThreadPool threadPool = new ThreadPool(2, 1);
        try{
           ss = new ServerSocket(8899);
           while(true){
               //接收客户端
               Socket socket = ss.accept();
               clints.add(socket);
               System.out.println(socket.getRemoteSocketAddress()+"上线了！");
               //启动
               threadPool.execute(new Tasker(socket,clints));
               //判断是否达到线程池最大任务执行数
               if(clints.size() == MAX_CLIENT){
                   ss.close();
                   ss=null;
                   //等待,main主线程进入阻塞状态
                   try {
                       TimeUnit.SECONDS.sleep(10);
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
                  ss = new ServerSocket(8899);
               }

           }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
